/**
 * Created by lijizhuang on 16/9/3.
 */
//可预定
define(['jquery', 'underscore', 'backbone', 'common', 'url', 'bootstrap', 'text!modules/dashboard/contextMenu/bookableMenuView.html',
    'modules/dashboard/modal/newReserve', 'plugins/jedate', 'extensions/dateExts'],
    function ($, _, Backbone, Common, Url, Bootstrap, BookableMenuViewTemplate, NewReserveView, jeDate, DateExts) {
        var bookableMenuView = Backbone.View.extend({
            tagName: 'ul',
            id: 'bookableMenu',
            className: 'contextMenu',

            template: _.template(BookableMenuViewTemplate),

            initialize: function (attrs) {
                _this = this;
                this.options = attrs;
            },

            events: {
                'click #newOrder': 'onCreateOrder',
                'click #lockRoom': 'onLockRoom'
            },

            onCreateOrder: function (e) {
                console.log('新建预定');

                //设置时间
                var fromDate = new Date(this.model.fromDate.replace(/-/g, "/"));
                var toDate = new Date(this.model.toDate.replace(/-/g, "/"));
                var today = new Date();
                var fromDiffDays = fromDate.diffInDays(today); //用户选择的起始时间距离今天的天数
                var toDiffDays = toDate.diffInDays(today); //用户选择的截止时间距离今天的天数
                var maxDate = fromDate.twoMonthLater(); //最多可以预订最近两个月的

                var duration = Math.abs(toDiffDays - fromDiffDays);
                this.model.duration = duration; //间夜数

                var postModel = {};
                postModel.fromTime = this.model.fromDate;
                postModel.toTime = this.model.toDate;
                postModel.roomTypeId = this.model.roomTypeId;
                //根据this.model.fromDate和this.model.toDate来查询这段时间的房价,从而计算出房费总价
                Common.sendAjaxRequest(Url.listCustomDailyPrice, postModel, _.bind(function (data) {
                    if (data.Content && data.Content.length > 0){
                        var priceArr = JSON.parse(data.Content);
                        if (priceArr.length > 0) {
                            var sum = _.reduce(priceArr, function (memo, num) { return memo + num; }, 0);
                            sum = parseFloat(sum).toFixed(2);
                            $('.consumeSum div span:last').text(sum);
                            $('.new-reserve-footer div span:last').text(sum);
                            $('#roomCosts').val(parseInt(sum));
                        }
                    }
                }, this), _.bind(function(data){
                    if (data.Content && data.Content.length > 0){
                        //错误处理
                    }
                }, this), true, true, true);

                var newReserveView = new NewReserveView({ model: this.model, collection: this.options.collection });
                if ($('body').find('#newReserve').length === 0) {
                    $('body').append(newReserveView.render().el);
                }
                else {
                    $('#newReserve').replaceWith(newReserveView.render().el);
                }

                $("#newReserve").modal({ backdrop: 'static', keyboard: false });

                var start = {
                    dateCell: "#fromDate",
                    festival: true,
                    isinitVal: true,
                    initAddVal: [fromDiffDays, "DD"], //初始化时间默认为用户选中的时间
                    minDate: today.yyyyMMdd(), //最小可选择时间设置成今天
                    maxDate: maxDate.yyyyMMdd(), //最大预订周期不超过两个月
                    isClear: false,
                    isToday: false,
                    format: 'YYYY-MM-DD',
                    choosefun: _.bind(function (elem, val) {
                        ////确保截止日不小于起始日
                        tempDate = new Date(val.replace(/-/g, "/"));
                        var tempDateStr = tempDate.tomorrow().yyyyMMdd();
                        end.minDate = tempDateStr;

                        if (val >= $('#toDate').val()) {
                            $('#toDate').val(tempDateStr);
                        }

                        //根据$('#fromDate')和$('#toDate')的值来查询这段时间的房价,从而修改出房费总价
                        var postModel = {};
                        postModel.fromTime = $('#fromDate').val();
                        postModel.toTime = $('#toDate').val();
                        postModel.roomTypeId = this.model.roomTypeId;
                        //根据this.model.fromDate和this.model.toDate来查询这段时间的房价,从而计算出房费总价
                        Common.sendAjaxRequest(Url.listCustomDailyPrice, postModel, _.bind(function (data) {
                            if (data.Content && data.Content.length > 0) {
                                var priceArr = JSON.parse(data.Content);
                                if (priceArr.length > 0) {
                                    var sum = _.reduce(priceArr, function (memo, num) { return memo + num; }, 0);
                                    sum = parseFloat(sum).toFixed(2);
                                    $('.consumeSum div span:last').text(sum);
                                    $('.new-reserve-footer div span:last').text(sum);
                                    $('#roomCosts').val(parseInt(sum));
                                }
                            }
                        }, this), _.bind(function (data) {
                            if (data.Content && data.Content.length > 0) {
                                //错误处理
                            }
                        }, this), true, true, true);

                        //修改间夜数
                        this.updateNightCount();
                    }, this)
                };

                var end = {
                    dateCell: "#toDate",
                    festival: true,
                    isinitVal: true,
                    initAddVal: [toDiffDays, "DD"],
                    minDate: toDate.yyyyMMdd(), //最小可选择时间设置成今天
                    maxDate: maxDate.yyyyMMdd(), //最大预订周期不超过两个月
                    isClear: false,
                    isToday: false,
                    format: 'YYYY-MM-DD',
                    choosefun: _.bind(function (elem, val) {
                        //根据$('#fromDate')和$('#toDate')的值来查询这段时间的房价,从而修改出房费总价
                        var postModel = {};
                        postModel.fromTime = $('#fromDate').val();
                        postModel.toTime = $('#toDate').val();
                        postModel.roomTypeId = this.model.roomTypeId;
                        //根据this.model.fromDate和this.model.toDate来查询这段时间的房价,从而计算出房费总价
                        Common.sendAjaxRequest(Url.listCustomDailyPrice, postModel, _.bind(function (data) {
                            if (data.Content && data.Content.length > 0) {
                                var priceArr = JSON.parse(data.Content);
                                if (priceArr.length > 0) {
                                    var sum = _.reduce(priceArr, function (memo, num) { return memo + num; }, 0);
                                    sum = parseFloat(sum).toFixed(2);
                                    $('.consumeSum div span:last').text(sum);
                                    $('.new-reserve-footer div span:last').text(sum);
                                    $('#roomCosts').val(parseInt(sum));
                                }
                            }
                        }, this), _.bind(function (data) {
                            if (data.Content && data.Content.length > 0) {
                                //错误处理
                            }
                        }, this), true, true, true);

                        //修改间夜数
                        this.updateNightCount();
                    }, this)
                };

                jeDate(start);
                jeDate(end);

                _this.removeView();
            },

            onLockRoom: function () {
                console.log('关闭房间');
                _this.removeView();
            },

            updateNightCount: function () {
                var fromDate = new Date($('#fromDate').val().replace(/-/g, "/"));
                var toDate = new Date($('#toDate').val().replace(/-/g, "/"));
                var diffDays = fromDate.diffInDays(toDate);
                $('.nightCount').html(diffDays + '晚');
            },

            render: function () {
                var model = this.model;
                $(this.el).html(this.template(model));
                return this;
            },

            showView: function () {
                $(_this.el).show().css({
                    'top': _this.model.top + 'px',
                    'left': _this.model.left + 'px'
                });
            },

            removeView: function () {
                $(_this.el).remove();
            }
        });

        return bookableMenuView;
    });